from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info.commons import user_login_data
from info.models import News, User
from info.utils.response_code import RET
from . import news_blue


@news_blue.route("/<int:news_id>")
def news_detail(news_id):
    user_id = session.get('user_id')
    user = None
    if user_id:
        user = User.query.get(user_id)
    # 根据新闻编号获取新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取新闻失败')
    # 判断是否存在
    if not news:
        abort(404)

    # 判断当前新闻是否在用户收藏列表中
    is_collected = False
    if user and news in user.collection_news:
        is_collected = True

    # 将新闻对象转换成字典数据
    data = {
        "news_info": news.to_dict(),
        "user_info": user.to_dict() if user else '',
        'is_collected': is_collected
    }
    # 携带数据渲染页面

    return render_template("news/detail.html", data=data)


@news_blue.route("/news_collect", methods=['POST'])
@user_login_data
def news_collect():
    if not g.user:
        return jsonify(errno=RET.PARAMERR, errmsg='用户未登陆')
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询新闻失败")
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg="新闻不存在")

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.DATAERR, errmsg="操作类型有误")
